<?php

class Article extends CActiveRecord
{
	/**
	 * The followings are the available columns in table 'articles':
	 * @var integer $id
	 * @var string $site
	 * @var string $title
	 * @var string $alias
	 * @var string $icon
	 * @var string $author
	 * @var string $moderator
	 * @var string $created
	 * @var string $updated
	 * @var string $publicated
	 * @var string $preamble
	 * @var string $preamble_marked
	 * @var string $text
	 * @var string $text_marked
	 * @var integer $comments
	 * @var string $source
	 * @var string $source_link
	 * @var integer $rating
	 * @var double $views
	 */

	public $_tag = array();
	public $preid = 'art';

	
	var $_sizes = array(
		'orig',
		'small'=>array(125,125),
		'normal'=>array(220,165),
		'big'=>array(300,200),
	);
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'articles';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title, alias, author, created, publicated, text, preid', 'required'),
			array('comments', 'numerical', 'integerOnly'=>true),
			array('title, source_link', 'length', 'max'=>255),
			array('alias', 'unique'),
			array('alias', 'match', 'pattern'=>'/[0-9a-z\-]+/is'),
			array('alias, author, moderator, source', 'length', 'max'=>45),
			array('preamble, preamble_marked, updated, text_marked, _tag', 'safe'),

			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id,  title, alias, author, moderator, created, updated, publicated, preamble, preamble_marked, text, text_marked, comments, source, source_link', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'tags'=>array(self::MANY_MANY, 'Tag', 'articles_tags(article_id, tag_id)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'title' => 'Название',
			'alias' => 'Псевдоним',
			'icon' => 'Картинка',
			'preamble' => 'Преамбула',
			'preamble_marked' => 'Обработанная преамбула',
			'author' => 'Автор',
			'moderator' => 'Модератор',
			'created' => 'Дата создания',
			'updated' => 'Дата последнего редактирования',
			'publicated' => 'Дата публикации',
			'text' => 'Текст',
			'text_marked' => 'Обработанный текст',
			'_tag' => 'Тэги',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);

		$criteria->compare('title',$this->title,true);

		$criteria->compare('alias',$this->alias,true);

		$criteria->compare('author',$this->author,true);

		$criteria->compare('moderator',$this->moderator,true);

		$criteria->compare('created',$this->created,true);

		$criteria->compare('updated',$this->updated,true);

		$criteria->compare('publicated',$this->publicated,true);

		$criteria->compare('preamble',$this->preamble,true);

		$criteria->compare('preamble_marked',$this->preamble_marked,true);

		$criteria->compare('text',$this->text,true);

		$criteria->compare('text_marked',$this->text_marked,true);

		$criteria->compare('source',$this->source,true);

		$criteria->compare('source_link',$this->source_link,true);

		return new CActiveDataProvider('Article', array(
			'criteria'=>$criteria,
		));
	}
	
	public function afterFind(){
		parent::afterFind();
		
		if(!empty($this->tags)){
			foreach($this->tags as $tag){
				$this->_tag[] = $tag->tag;
			}
		}
	}
	
	public function beforeValidate(){
		Yii::import('ext.markdown.*');
		$md = new EMarkdown;
		$this->text_marked = $md->transform($this->text);
		if($this->preamble)
			$this->preamble_marked = $md->transform($this->preamble);
		return parent::beforeValidate();
	}
	
	public function beforeSave(){
		if($this->isNewRecord)
			$this->created = date('Y-m-d H:i:s');
		else {
			$this->updated = date('Y-m-d H:i:s');
			$this->moderator = Yii::app()->user->name;
		}
		
		return parent::beforeSave();
	}
	
	public function afterSave(){
		$this->saveTag();
		return parent::afterSave();
	}
	
	public function afterDelete(){
		$at = ArticlesTags::model()->findAll('article_id=:article_id',array(':article_id'=>$this->id));
		foreach($at as $item){
			// Если тега нет в возвращенных
			if($item->tag->frequency <= 1) {
				// Удаляю теги и связь у которых вес 1
				$item->tag->delete();
				$item->delete();
			} else {
				// Теги у которых вес больше 1, вычетаются единица и удаляется связь
				$item->tag->frequency -= 1;
				$item->tag->save();
				$item->delete();
			}
		}
		
		return parent::afterDelete();
	}

	protected function saveTag(){
		if($this->_tag){

			$at = ArticlesTags::model()->findAll('article_id=:article_id',array(':article_id'=>$this->id));
			foreach($at as $item){
				if(in_array($item->tag->tag, $this->_tag)){
					// Если тег есть в таблице и в возвращенных из формы то все остается по прежнему 
					continue;
				} else {
					// Если тега нет в возвращенных
					if($item->tag->frequency <= 1) {
						// Удаляю теги и связь у которых вес 1
						$item->tag->delete();
						$item->delete();
					} else {
						// Теги у которых вес больше 1, вычетаются единица и удаляется связь
						$item->tag->frequency -= 1;
						$item->tag->save();
						$item->delete();
					}
				}
			}
			
			foreach($this->_tag as $word){
				if($tag = Tag::model()->find('tag=:tag', array(':tag'=>$word))){
					if(!ArticlesTags::model()->exists('article_id=:article_id and tag_id=:tag_id', array(':article_id'=>$this->id, ':tag_id'=>$tag->id))){
						// Если тег в таблице есть но связи нет
						// добавляем связь и увеличиваем вес тега
						$ArticlesTags = new ArticlesTags;
						$ArticlesTags->article_id = $this->id;
						$ArticlesTags->tag_id = $tag->id;
						$ArticlesTags->save();
						$tag->frequency += 1;
						$tag->save();
					}
				} else {
					// Если тега нет в таблцице то добавляю тег и связь
					$tag = new Tag;
					$tag->tag = $word;
					$tag->frequency = 1;
					$tag->save();
					$ArticlesTags = new ArticlesTags;
					$ArticlesTags->article_id = $this->id;
					$ArticlesTags->tag_id = $tag->id;
					$ArticlesTags->save();
				}
			}
		}
	}
}